package dao

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go-admin/base/utils"
	"strings"
)

var _ PermissionModel = (*customPermissionModel)(nil)

type (
	// PermissionModel is an interface to be customized, add more methods here,
	// and implement the added methods in customPermissionModel.
	PermissionModel interface {
		permissionModel
		FindAll(ctx context.Context) ([]*Permission, error)
		FindByPermissionIds(ctx context.Context, permissionIds []int64) ([]*Permission, error)
		UpdateNameById(ctx context.Context, data *Permission) error
	}

	customPermissionModel struct {
		*defaultPermissionModel
	}
)

func (c customPermissionModel) UpdateNameById(ctx context.Context, data *Permission) error {
	query := fmt.Sprintf("update %s set %s where `id` = ?", c.table, " name=?,number=? ")
	_, err := c.conn.ExecCtx(ctx, query, data.Name, data.Number, data.Id)
	return err
}

func (c customPermissionModel) FindAll(ctx context.Context) ([]*Permission, error) {
	query := fmt.Sprintf("select %s from %s ", permissionRows, c.table)
	var resp []*Permission
	err := c.conn.QueryRowsCtx(ctx, &resp, query)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c customPermissionModel) FindByPermissionIds(ctx context.Context, permissionIds []int64) ([]*Permission, error) {
	//query := fmt.Sprintf("select %s from %s where `id` in ( ? )  ", permissionRows, c.table)
	query := fmt.Sprintf("select %s from %s where `id` in ( %s )  ", permissionRows, c.table, strings.Join(utils.GeneratePlaceholderByInt64(permissionIds), ","))
	var resp []*Permission
	err := c.conn.QueryRowsCtx(ctx, &resp, query, utils.ConvertToAny(permissionIds)...)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

// NewPermissionModel returns a model for the database table.
func NewPermissionModel(conn sqlx.SqlConn) PermissionModel {
	return &customPermissionModel{
		defaultPermissionModel: newPermissionModel(conn),
	}
}
